package com.cvmars.jianyou.module.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.cvmars.jianyou.R;
import com.cvmars.jianyou.api.api.Api;
import com.cvmars.jianyou.api.api.HttpUtils;
import com.cvmars.jianyou.api.api.SimpleSubscriber;
import com.cvmars.jianyou.api.model.HttpResult;
import com.cvmars.jianyou.config.MyConfig;
import com.cvmars.jianyou.model.ImageModel;
import com.cvmars.jianyou.model.ImageUploadModel;
import com.cvmars.jianyou.module.adapter.FindImageWeiboAdapter;
import com.cvmars.jianyou.module.base.BaseActivity;
import com.cvmars.jianyou.module.base.BaseImagePagerActivity;
import com.cvmars.jianyou.module.model.EventFindRefresh;
import com.cvmars.jianyou.utils.DensityUtils;
import com.cvmars.jianyou.utils.LogUtils;
import com.cvmars.jianyou.utils.QiNiuUtils;
import com.cvmars.jianyou.utils.ToastUtils;
import com.cvmars.jianyou.widget.SpacesItemDecoration;
import com.google.gson.Gson;
import com.suke.widget.SwitchButton;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class FindAddWeiboActivity extends BaseActivity {

    @BindView(R.id.list_image)
    RecyclerView listImage;
    @BindView(R.id.ed_content_publish)
    EditText edContentPublish;
    List<ImageModel> image;
    @BindView(R.id.txt_publish)
    TextView txtPublish;
    @BindView(R.id.switch_button)
    SwitchButton switchButton;

    @BindView(R.id.txt1)
    TextView txt1;
    @BindView(R.id.txt_topic)
    TextView txtTopic;

    boolean is_hidden_name;

    private String mStrTopic;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_add_weibo);
        ButterKnife.bind(this);
        mStrTopic = getIntent().getStringExtra("topic");
        LogUtils.d("topic :" + mStrTopic);

        if (mStrTopic != null) {
            txtTopic.setText(mStrTopic);
        }
        image = (List<ImageModel>) getIntent().getSerializableExtra("list");
        FindImageWeiboAdapter imgAdapter = new FindImageWeiboAdapter(this, R.layout.item_find_img, image);
        listImage.setLayoutManager(new GridLayoutManager(this, 3));
        listImage.addItemDecoration(new SpacesItemDecoration(DensityUtils.dp2px(this, 3)));
        listImage.setAdapter(imgAdapter);


        final List<ImageUploadModel> list = new ArrayList<>();
        if(image!=null){


            for (int i = 0; i < image.size(); i++) {


                ImageUploadModel imageUploadModel = new ImageUploadModel();

                imageUploadModel.url = image.get(i).imgPath;
                list.add(imageUploadModel);
            }


        }
        imgAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                Bundle bundle = new Bundle();
                bundle.putSerializable(MyConfig.INTENT_DATA_URL, (Serializable) list);
                Intent intent = new Intent(FindAddWeiboActivity.this, BaseImagePagerActivity.class);
                intent.putExtra("position", position);
                intent.putExtras(bundle);
                startActivity(intent);

            }
        });
        switchButton.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {

                is_hidden_name = isChecked;
            }
        });

        edContentPublish.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                if (charSequence.length() == 0) {

                    txtPublish.setTextColor(ContextCompat.getColor(FindAddWeiboActivity.this, R.color.color666));

                    txtPublish.setBackgroundResource(0);
                } else {

                    txtPublish.setTextColor(Color.WHITE);
                    txtPublish.setBackgroundResource(R.drawable.shape_send_select);

                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }


    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            List<ImageModel> list = (List<ImageModel>) msg.obj;

            String content = edContentPublish.getText().toString();

            if (TextUtils.isEmpty(content)) {
                ToastUtils.show("请输入内容");
                return;
            }


            String images = "";
            if (list != null) {

                List<ImageUploadModel> listup = new ArrayList<>();

                for (int i = 0; i < list.size(); i++) {

                    ImageUploadModel model = new ImageUploadModel();
                    model.url = MyConfig.QINIU_HOST + list.get(i).uploadPath;
                    model.w = list.get(i).w + "";
                    model.h = list.get(i).h + "";
                    listup.add(model);
                }

                images = new Gson().toJson(listup);
            }


            HttpUtils.getInstance().toSubscribe(Api.getInstance().postPublishFind(mStrTopic, content, is_hidden_name, images)
                    , new SimpleSubscriber<HttpResult<Object>>() {
                        @Override
                        protected void _onNext(HttpResult<Object> o) {

                            getLoadDialogAndDismiss();
                            ToastUtils.show("发布成功");
                            EventBus.getDefault().post(new EventFindRefresh(true));
                            finish();
                        }

                        @Override
                        protected void _onError(String message) {

                        }
                    });

        }
    };

    @OnClick(R.id.txt_publish)
    public void onViewClicked() {
        String content = edContentPublish.getText().toString();

        if (TextUtils.isEmpty(content)) {
            ToastUtils.show("请输入内容");
            return;
        }
        getLoadDialogAndShow();

        if (image == null || image.size() == 0) {

            HttpUtils.getInstance().toSubscribe(Api.getInstance().postPublishFind(mStrTopic, is_hidden_name, content)
                    , new SimpleSubscriber<HttpResult<Object>>() {
                        @Override
                        protected void _onNext(HttpResult<Object> o) {

                            getLoadDialogAndDismiss();
                            ToastUtils.show("发布成功");
                            EventBus.getDefault().post(new EventFindRefresh(true));
                            finish();
                        }

                        @Override
                        protected void _onError(String message) {

                        }
                    });

        } else {

            QiNiuUtils.getInstance().initImage(image, handler);
        }
    }

    public void onTopic(View view) {


        startActivityForResult(new Intent(this, FindTopicSelectActivity.class), 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1) {

            txtTopic.setText("#" + data.getStringExtra("topic") + "#");
            mStrTopic = "#" + data.getStringExtra("topic") + "#";
        }
    }
}
